package com.jxlc.web.api.system.domain.entity;

import com.baomidou.mybatisplus.annotation.TableId;
import com.jxlc.common.config.ConfigConst;
import com.jxlc.common.exception.GlobalException;
import com.jxlc.common.utils.SecurityUtils;
import com.jxlc.common.utils.file.FileUploadUtils;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.multipart.MultipartFile;

import java.io.Serializable;
import java.util.Date;

/**
 * sys_file
 */
@Data
@NoArgsConstructor
public class SysFile implements Serializable {
    /**
     * 文件ID
     */
    @TableId
    private Long id;

    /**
     * 文件编号
     */
    private String fileNo;

    /**
     * 源文件名
     */
    private String originName;

    /**
     * 文件名
     */
    private String fileName;

    /**
     * 文件类型
     */
    private String fileType;

    /**
     * 文件大小
     */
    private long fileSize;

    /**
     * 文件来源
     */
    private String fileOrigin;

    /**
     * 路径
     */
    private String filePath;

    /**
     * 上传者
     */
    private Long uploadBy;

    /**
     * 上传时间
     */
    private Date uploadTime;

    /**
     * 源路径
     */
    private String originPath;

    private static final long serialVersionUID = 1L;

    public SysFile(MultipartFile file) throws Exception {
        this.originName = file.getOriginalFilename();
        if (originName == null) {
            throw new GlobalException("文件名不能为空");
        }
        this.fileName = originName.substring(0, originName.lastIndexOf("."));
        if (fileName.length() > 180) {
            fileName = fileName.substring(0, 180);
        }
        this.fileSize = file.getSize();
        String baseDir = ConfigConst.getUploadPath();
        this.filePath = FileUploadUtils.upload(baseDir, file);
        this.fileType = FileUploadUtils.getExtension(file);
        if (fileType.length() > 8) {
            this.fileType = fileType.substring(0, 7);
        }
        this.fileNo = "F" + System.currentTimeMillis();
        this.uploadTime = new Date();
        this.uploadBy = SecurityUtils.getUserId();
    }
}